#include "ImageView.h"
#include <QResizeEvent>
#include <QPaintEvent>
#include <QPainter>

ImageView::ImageView(QWidget *parent)
    : QWidget(parent)
    , _path(""){

}
ImageView::ImageView(const QString &path, QWidget *parent)
    : QWidget(parent)
    , _path(path)
    , _pixmap(path){
}
ImageView::~ImageView(){
}

void ImageView::reset(const QString &path){
    _path = path;
    this->repaint();
}

void ImageView::resizeEvent(QResizeEvent *event){
    QWidget::resizeEvent(event);
}
void ImageView::paintEvent(QPaintEvent *event){
    if(_path.isEmpty()){
        QWidget::paintEvent(event);
        return;
    }

    QSize targetSize = this->size();
    QPixmap pixmapAfterScale = loadImage(_path,targetSize);
    qreal x = (targetSize.width() - pixmapAfterScale.width()) * 0.5;
    qreal y = (targetSize.height() - pixmapAfterScale.height()) * 0.5;
    QPainter painter(this);
    painter.drawPixmap(QPointF(x,y),pixmapAfterScale);

}
QPixmap ImageView::loadImage(const QString &path, const QSize &size){
    QImageReader imageReader;
    imageReader.setFileName(path);

    auto srcSize = imageReader.size();
    auto destSize = srcSize.scaled(size,Qt::KeepAspectRatio);

    imageReader.setScaledSize(destSize);
    return QPixmap::fromImageReader(&imageReader);
}
